package com.lagou.rocket.demo.seckill.service.Impl;

import com.lagou.rocket.demo.seckill.common.SnowflakeIdWorker;
import com.lagou.rocket.demo.seckill.model.Order;
import com.lagou.rocket.demo.seckill.service.IInventoryService;
import com.lagou.rocket.demo.seckill.service.ISecKillService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *
 * </p>
 *
 * @author KK
 * @since 2021-11-06
 */
@Slf4j
@Service
public class SecKillServiceImpl implements ISecKillService {

    private final IInventoryService inventoryService;
    private final SnowflakeIdWorker snowflakeIdWorker;
    private final RocketMQTemplate rocketMQTemplate;

    public SecKillServiceImpl(IInventoryService inventoryService,
                              SnowflakeIdWorker snowflakeIdWorker,
                              RocketMQTemplate rocketMQTemplate) {
        this.inventoryService = inventoryService;
        this.snowflakeIdWorker = snowflakeIdWorker;
        this.rocketMQTemplate = rocketMQTemplate;
    }

    @Override
    public Long seckill(Long userId, String productCode, Integer num) {

        // 预检查库存(redis)
        boolean hasInventory = inventoryService.preCheckInventory(productCode);

        if (!hasInventory) {
            //  返回已经售罄;
            return null;
        }

        //   生成一个订单id（这个id并不代表真正下单成功， 只是预先生成）
        long orderId = snowflakeIdWorker.nextId();

        //   发送下单消息(orderId, userId, productCode, num);
        Order order = new Order();
        order.setId(orderId);
        order.setUserId(userId);
        order.setProductCode(productCode);
        order.setNum(num);
        final SendResult sendResult = this.rocketMQTemplate.syncSend("seckill",
                order);
        if (!SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            log.error("秒杀服务下单消息发送失败");
            return null;
        }
        log.info("发送下单消息成功, msgId: {}", sendResult.getMsgId());

        //   返回订单id;
        return orderId;
    }
}
